import type { SelectorQuery } from '@tarojs/taro'
import { nextTick } from '@tarojs/taro'

export default function getNodeSize(
  querySelector: string,
): Promise<{ height: number; width: number }> {
  return new Promise(function (resolve) {
    nextTick(() => {
      // 数据渲染
      nextTick(() => {
        // 视图渲染
        wx.createSelectorQuery()
          .select(querySelector)
          .fields({ size: true })
          .exec(function (res) {
            resolve(res[0])
          })
      })
    })
  })
}

// 缓存查询到的 node
export class NodeSize {
  node: SelectorQuery
  constructor(querySelector) {
    this.node = wx.createSelectorQuery().select(querySelector).fields({ size: true })
  }

  getSize(): Promise<{ height: number; width: number }> {
    return new Promise((resolve) => {
      this.node.exec(function (res) {
        resolve(res[0])
      })
    })
  }
}
